// 文件分片
export function sliceFile(file, chunkSize) {
  return new Promise((resolve, reject) => {
    let fileSize = file.size;
    let offset = 0;
    let chunkIndex = 0;
    let chunks = [];

    let reader = new FileReader();

    reader.onload = function (event) {
      let chunk = event.target.result;
      chunks.push(chunk);

      offset += chunk.byteLength;
      chunkIndex++;

      if (offset < fileSize) {
        readNextChunk();
      } else {
        resolve(chunks);
      }
    };

    reader.onerror = function (event) {
      reject(event.target.error);
    };

    function readNextChunk() {
      let chunk = file.slice(offset, offset + chunkSize);
      reader.readAsArrayBuffer(chunk);
    }
    readNextChunk();
  });
}


// 文件合并
export function mergeArrayBuffersToBlob(arrayBuffers) {
  const combinedArray = new Uint8Array(
      arrayBuffers.reduce((totalLength, buffer) => totalLength + buffer.byteLength, 0)
  );
  let offset = 0;
  for (const buffer of arrayBuffers) {
    combinedArray.set(new Uint8Array(buffer), offset);
    offset += buffer.byteLength;
  }
  // 使用 Blob 构造函数创建一个新的 Blob 对象
  return new Blob([combinedArray], {type: 'application/octet-stream'});
}
